from re import X
from flask import request,jsonify,Blueprint
from database import *
from conf.comm import sqlalchemy_context
import json


bp_course = Blueprint('course',__name__)

def xtree(data):
    tree = {}
    list = []
    if data:
        #解析成字典
        for i in data:
            tree[i['id']] = i
        
        for j in data:
            #判断有没有 父id 没有的话 就是顶级的 直接加入
            if j['parent'] == 0:
                list.append(j)
            else:
                #判断有没有儿子，没有的话创建一个列表
                if 'son' not in tree[j['parent']]:
                    tree[j['parent']]['son'] = []
                #有的话 直接在后边填
                tree[j['parent']]['son'].append(j)

        return list


@bp_course.route('/add_cate',methods=['POST','GET'])
@sqlalchemy_context()
def add_cate():
    if request.method == "POST":
        try:
            data = request.data
            if data:
                data = json.loads(data)
            else:
                data = request.form
            
            
            try:
                params = data['params']
            except:
                params = ""
            cate = Cate(name=data['name'],types=data['types'],parent=data['parent'],params=params)
            db.session.add(cate)
            db.session.commit()
            return jsonify({'code':200})
        except:
            return jsonify({'code':10010})
    else:
        cate = Cate.query.all()
        list = []
        for i in cate:
            dict = {"id":i.id,"name":i.name,"types":i.types,"parent":i.parent,"params":i.params}
            list.append(dict)
        list1 = xtree(list)
        return jsonify({'code':200,'list':list1})
